import 'package:fl_chart/fl_chart.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:xuance/RoutePath.dart';
import 'package:xuance/bean/TimeEnum.dart';
import 'package:xuance/constant.dart';
import 'package:xuance/generated/assets.dart';
import 'package:xuance/page/warning_detail/logic.dart';
import 'package:xuance/util/ChartUtil.dart';
import 'package:xuance/widget/EmptyWidget.dart';

import 'logic.dart';

class HomePage extends StatelessWidget {
  const HomePage({super.key});

  @override
  Widget build(BuildContext context) {
    final logic = Get.find<HomeLogic>();
    final state = logic.state;
    return Stack(children: [
      SizedBox(
          height: 380,
          width: double.infinity,
          child: Stack(children: [
            Positioned.fill(
                child: Image.asset(Assets.assetsHomeBg, fit: BoxFit.fill))
          ])),
      Positioned(
          top: 200,
          left: 20,
          right: 20,
          bottom: 0,
          child: Column(children: [
            PopupMenuButton(
                itemBuilder: (BuildContext context) {
                  return TimeEnum.values
                      .map((m) => PopupMenuItem(value: m, child: Text(m.desc)))
                      .toList();
                },
                onSelected: (v) {
                  state.dateType.value = v;
                  logic.init();
                },
                child: Row(children: [
                  Image.asset(Assets.assetsTimeIcon, scale: 2.5),
                  const SizedBox(width: 5),
                  Obx(() {
                    return Text(state.dateType.value.desc,
                        style: TextStyle(color: titleColor, fontSize: 14));
                  }),
                  Icon(Icons.keyboard_arrow_down, color: c_979797)
                ])),
            const SizedBox(height: 10),
            Expanded(
                child: SingleChildScrollView(
                    child: Column(children: [
              Obx(() {
                if (!state.isExpand.value) {
                  return Container(
                    padding: const EdgeInsets.all(10),
                    decoration: BoxDecoration(
                        gradient: const LinearGradient(
                            begin: Alignment.topCenter,
                            end: Alignment.bottomCenter,
                            colors: [
                              Color.fromARGB(25, 95, 215, 174),
                              Color.fromARGB(10, 95, 215, 174)
                            ]),
                        borderRadius: BorderRadius.circular(5)),
                    child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Image.asset(Assets.assetsAiWarningTitle, scale: 3),
                          InkWell(
                              onTap: () {
                                state.isExpand.value = true;
                              },
                              child: Padding(
                                  padding: const EdgeInsets.all(8.0),
                                  child: Icon(Icons.keyboard_arrow_down_rounded,
                                      color: c_green)))
                        ]),
                  );
                }
                return Stack(children: [
                  Container(
                      padding: const EdgeInsets.all(10),
                      decoration: BoxDecoration(
                          gradient: const LinearGradient(
                              begin: Alignment.topCenter,
                              end: Alignment.bottomCenter,
                              colors: [
                                Color.fromARGB(25, 95, 215, 174),
                                Color.fromARGB(10, 95, 215, 174)
                              ]),
                          borderRadius: BorderRadius.circular(5)),
                      child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Image.asset(Assets.assetsAiWarningTitle, scale: 3),
                            Row(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: [
                                  Obx(() {
                                    return Text(
                                        state.aiWarnChart.isEmpty
                                            ? '0'
                                            : "${state.aiWarnChart.map((m) => m.warnCount?.toInt() ?? 0).reduce((a, b) => a + b)}",
                                        style: const TextStyle(
                                            fontSize: 25,
                                            fontWeight: FontWeight.bold,
                                            color: Colors.white));
                                  }),
                                ]),
                            const SizedBox(height: 5),
                            AspectRatio(
                                aspectRatio: 2.1,
                                child: Obx(() {
                                  if (state.aiWarnChart.isEmpty) {
                                    return Container();
                                  }
                                  return LineChart(ChartUtil.getWarningChart(
                                      blockips: state.aiWarnChart.value,
                                      currentWarning: state.dateType.value));
                                }))
                          ])),
                  Positioned(
                      right: 10,
                      top: 10,
                      child: InkWell(
                          onTap: () {
                            state.isExpand.value = false;
                          },
                          child: Padding(
                              padding: const EdgeInsets.all(8.0),
                              child: Icon(Icons.keyboard_arrow_up_rounded,
                                  color: c_green))))
                ]);
              }),
              const SizedBox(height: 20),
              Container(
                  padding: const EdgeInsets.all(10),
                  decoration: BoxDecoration(
                      gradient: const LinearGradient(
                          begin: Alignment.topCenter,
                          end: Alignment.bottomCenter,
                          colors: [
                            Color.fromARGB(25, 95, 215, 174),
                            Color.fromARGB(10, 95, 215, 174)
                          ]),
                      borderRadius: BorderRadius.circular(5)),
                  child: Column(children: [
                    Align(
                      alignment: Alignment.centerLeft,
                      child:
                          Image.asset(Assets.assetsWarningListTitile, scale: 3),
                    ),
                    const SizedBox(height: 10),
                    Obx(() {
                      if (state.aiWarningList.isEmpty) {
                        return const EmptyWidget();
                      }
                      return ListView.builder(
                          shrinkWrap: true,
                          padding: EdgeInsets.zero,
                          physics: const NeverScrollableScrollPhysics(),
                          itemCount: state.aiWarningList.length,
                          itemBuilder: (BuildContext context, int index) {
                            var bean = state.aiWarningList[index];
                            return InkWell(
                                onTap: () {
                                  Get.toNamed(RoutePath.warningDetail,
                                      arguments: TrafficDetailBean(
                                          bean: bean,
                                          type: state.dateType.value,
                                          queryCondition:
                                              state.queryCondition.value,
                                          isWarnDetail: true));
                                },
                                child: DefaultTextStyle(
                                    style: TextStyle(color: c_9EA1A6),
                                    child: Container(
                                        color: index % 2 == 0
                                            ? const Color(0xff233F48)
                                            : Colors.transparent,
                                        child: SingleChildScrollView(
                                            scrollDirection: Axis.horizontal,
                                            child: Row(children: [
                                              Padding(
                                                  padding:
                                                      const EdgeInsets.all(8.0),
                                                  child: Obx(() {
                                                    return Text(
                                                        "序号:${(logic.aiWarningListPage.value - 1) * state.aiWarningListTotalPage.value + index + 1}");
                                                  })),
                                              Padding(
                                                  padding:
                                                      const EdgeInsets.all(8.0),
                                                  child: Text(
                                                      "类型:${bean.sceneType}")),
                                              Padding(
                                                  padding:
                                                      const EdgeInsets.all(8.0),
                                                  child: Column(
                                                      crossAxisAlignment:
                                                          CrossAxisAlignment
                                                              .start,
                                                      children: [
                                                        Text(
                                                            "从：${bean.sip}:${bean.spt}"),
                                                        Text(
                                                            "到：${bean.dip}:${bean.dpt}")
                                                      ])),
                                              Padding(
                                                  padding:
                                                      const EdgeInsets.all(8.0),
                                                  child: Column(children: [
                                                    Text("XFFIP：${bean.xffIp}")
                                                  ])),
                                              Padding(
                                                  padding:
                                                      const EdgeInsets.all(8.0),
                                                  child: Container(
                                                      padding: const EdgeInsets
                                                          .symmetric(
                                                          horizontal: 5,
                                                          vertical: 3),
                                                      decoration: BoxDecoration(
                                                          color: Colors.white
                                                              .withAlpha(10),
                                                          borderRadius:
                                                              BorderRadius
                                                                  .circular(3)),
                                                      child: Row(
                                                          mainAxisSize:
                                                              MainAxisSize.min,
                                                          children: [
                                                            const Text("包数量"),
                                                            const SizedBox(
                                                                width: 5),
                                                            Column(children: [
                                                              Text(
                                                                  "源:${bean.spackets}"),
                                                              Text(
                                                                  "目:${bean.dpackets}"),
                                                            ])
                                                          ]))),
                                              Padding(
                                                  padding:
                                                      const EdgeInsets.all(8.0),
                                                  child: Container(
                                                      padding: const EdgeInsets
                                                          .symmetric(
                                                          horizontal: 5,
                                                          vertical: 3),
                                                      decoration: BoxDecoration(
                                                          color: Colors.white
                                                              .withAlpha(10),
                                                          borderRadius:
                                                              BorderRadius
                                                                  .circular(3)),
                                                      child: Row(
                                                          mainAxisSize:
                                                              MainAxisSize.min,
                                                          children: [
                                                            const Text("主体字节"),
                                                            const SizedBox(
                                                                width: 5),
                                                            Column(children: [
                                                              Text(
                                                                  "源:${bean.spayloadBytes}"),
                                                              Text(
                                                                  "目:${bean.dpayloadBytes}"),
                                                            ])
                                                          ])))
                                            ])))));
                          });
                    }),
                    Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          GestureDetector(
                              onTap: logic.lastPage,
                              child: const Padding(
                                  padding: EdgeInsets.all(8.0),
                                  child: Text("上一页",
                                      style: TextStyle(
                                          color: Color(0xff9EA1A6))))),
                          Obx(() {
                            return Text(
                                "第${logic.aiWarningListPage.value}页,共${state.aiWarningListTotalPage.value}页",
                                style:
                                    const TextStyle(color: Color(0xff9EA1A6)));
                          }),
                          GestureDetector(
                              onTap: logic.nextPage,
                              child: Padding(
                                  padding: const EdgeInsets.all(8.0),
                                  child: Text("下一页",
                                      style: TextStyle(color: c_green))))
                        ])
                  ])),
              const SizedBox(height: 20),
              Container(
                  padding: const EdgeInsets.all(10),
                  decoration: BoxDecoration(
                      gradient: const LinearGradient(
                          begin: Alignment.topCenter,
                          end: Alignment.bottomCenter,
                          colors: [
                            Color.fromARGB(25, 95, 215, 174),
                            Color.fromARGB(10, 95, 215, 174)
                          ]),
                      borderRadius: BorderRadius.circular(5)),
                  child: Column(children: [
                    Align(
                        alignment: Alignment.centerLeft,
                        child:
                            Image.asset(Assets.assetsAiEventFeature, scale: 3)),
                    const SizedBox(height: 10),
                    Row(children: [
                      Expanded(
                          flex: 3,
                          child: AspectRatio(
                              aspectRatio: 1,
                              child: Obx(() {
                                return PieChart(PieChartData(
                                    pieTouchData: PieTouchData(touchCallback:
                                        (FlTouchEvent event, pieTouchResponse) {
                                      if (!event.isInterestedForInteractions ||
                                          pieTouchResponse == null ||
                                          pieTouchResponse.touchedSection ==
                                              null) {
                                        state.touchedtypeCountIndex.value =
                                            null;
                                        return;
                                      }
                                      state.touchedtypeCountIndex.value =
                                          state.typeCount[pieTouchResponse
                                              .touchedSection!
                                              .touchedSectionIndex];
                                    }),
                                    borderData: FlBorderData(show: false),
                                    sectionsSpace: 10,
                                    centerSpaceRadius: 40,
                                    sections: state.typeCount.map((m) {
                                      final isTouched = m ==
                                          state.touchedtypeCountIndex.value;
                                      final fontSize = isTouched ? 25.0 : 16.0;
                                      final radius = isTouched ? 60.0 : 50.0;
                                      int all = state.typeCount
                                          .map((f) => f.nums?.toInt() ?? 0)
                                          .reduce((a, b) => a + b);
                                      int current = m.nums?.toInt() ?? 0;
                                      const double minPercentage = 4.0;
                                      double percentage = (current / all) * 100;
                                      double adjustedPercentage =
                                          percentage < minPercentage
                                              ? minPercentage
                                              : percentage;

                                      return PieChartSectionData(
                                          color: m.color,
                                          value: adjustedPercentage,
                                          title: "",
                                          radius: radius,
                                          titleStyle: TextStyle(
                                              fontSize: fontSize,
                                              fontWeight: FontWeight.bold,
                                              color: m.color,
                                              shadows: const [
                                                Shadow(
                                                    color: Colors.black,
                                                    blurRadius: 2),
                                              ]));
                                    }).toList()));
                              }))),
                      const SizedBox(width: 15),
                      Expanded(
                          flex: 2,
                          child: Obx(() {
                            return Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children:
                                    List.generate(state.typeCount.length, (i) {
                                  var bean = state.typeCount[i];
                                  int all = state.typeCount
                                      .map((f) => f.nums?.toInt() ?? 0)
                                      .reduce((a, b) => a + b);
                                  return Column(
                                      crossAxisAlignment:
                                          CrossAxisAlignment.start,
                                      children: [
                                        Obx(() {
                                          return Text("${bean.sceneType}",
                                              maxLines: 1,
                                              overflow: TextOverflow.ellipsis,
                                              style: TextStyle(
                                                  color: bean.color,
                                                  fontWeight:
                                                      state.touchedtypeCountIndex
                                                                  .value ==
                                                              bean
                                                          ? FontWeight.bold
                                                          : null,
                                                  fontSize:
                                                      state.touchedtypeCountIndex
                                                                  .value ==
                                                              bean
                                                          ? 18
                                                          : 12));
                                        }),
                                        Obx(() {
                                          return Text(
                                              "${(((bean.nums?.toInt() ?? 0) / all) * 100).toStringAsFixed(2)}% (${bean.nums})",
                                              maxLines: 1,
                                              style: TextStyle(
                                                  color: bean.color,
                                                  fontWeight:
                                                      state.touchedtypeCountIndex
                                                                  .value ==
                                                              bean
                                                          ? FontWeight.bold
                                                          : null,
                                                  fontSize:
                                                      state.touchedtypeCountIndex
                                                                  .value ==
                                                              bean
                                                          ? 18
                                                          : 12));
                                        })
                                      ]);
                                }));
                          }))
                    ]),
                    const SizedBox(height: 10)
                  ])),
              const SizedBox(height: 20)
            ])))
          ]))
    ]);
  }
}
